from flask import Blueprint, render_template, request, jsonify, session
# from utils.util import compress_image
import time
import os
from utils.database_util import query_data

article_publish = Blueprint('article_publish' ,__name__)

@article_publish.route('/article_publish/')
def index():
    return render_template("article_publish.html")

@article_publish.route(rule='/add_article', methods=['GET', 'POST'])
def add_article():
    userid = session.get ('userid')
    if userid is None:
        return "error"
    headline = request.form.get('headline')
    content = request.form.get('content')
    type = int(request.form.get('type'))
    credit = int(request.form.get('credit'))
    #drafted = int(request.form.get('drafted'))
    #checked = int(request.form.get('checked'))
    #articleid = int(request.form.get('articleid'))
    sql = "INSERT INTO `article`(`userid`, `type`, `headline`, `content`, `credit`) VALUES (%d, %d, '%s', '%s', %d)" %(userid, type, headline, content, credit)
    result = query_data(sql)
    return "OK"

@article_publish.route(rule='/uedit', methods=['GET', 'POST'])
def uedit():


    param = request.args.get('action')
    if request.method == 'GET' and param == 'config':
            return render_template('config.json')


    elif request.method == 'POST' and request.args.get('action') == 'uploadimage':
        f = request.files['upfile']
        filename = f.filename

        suffix = filename.split('.')[-1]
        newname = time.strftime('%Y%m%d_%H%M%S_' + suffix)
        f.save('./resource/upload/' + newname)



        source = dest = './resource/upload/' + newname
        #compress_image(source, dest, width=1200)


        result = {}
        result['state'] = 'SUCCESS'
        result['url'] = '/upload/{newname}'
        result['original'] = filename
        return jsonify(result)
    elif request.method == 'GET' and param == 'listimage':
        list = []
        filelist = os.listdir('./resource/upload')

        for filename in filelist:
            if filename.lower().endswith('.png') or filename.lower().endswith('.jpg'):
                list.append({'url': '/upload/%s' % filename})


            result = {}
            result['state'] = 'SUCCESS'
            result['list'] = list
            result['start'] = 0
            result['total'] = 50
            return jsonify(result)